package com.yupao.job;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupao.model.entity.User;
import com.yupao.model.vo.LoginUserVO;
import com.yupao.service.UserService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存预热
 */
@Component
public class ProCacheJob {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private RedissonClient redissonClient;

    //重点用户
    List<Long> userList = Collections.singletonList(1L);

    @Scheduled(cron = "0 35 0,4 * * *")
    public void doCacheRecommendUser(){
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        RLock lock = redissonClient.getLock("yupao:doCache:lock");

        try {
            //抢锁
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                for (Long id : userList) {
                    String keyStr = String.format("yupao:user:%s", id);
                    Page<User> userPage = userService.page(new Page<>(1, 2));
                    List<User> userList = userPage.getRecords();
                    List<LoginUserVO> loginUserVOList = new ArrayList<>();
                    for (User user : userList) {
                        LoginUserVO loginUserVO = new LoginUserVO();
                        BeanUtils.copyProperties(user, loginUserVO);
                        loginUserVOList.add(loginUserVO);
                    }
                    //将数据存入缓存
                    valueOperations.set(keyStr,loginUserVOList,300000, TimeUnit.MILLISECONDS);
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //判断是否为当前线程
            if (lock.isHeldByCurrentThread()) {
                //释放锁
                lock.unlock();
            }
        }
    }
}
